package com.rnd.kx.mvp.http.net;

import com.rnd.kx.mvp.http.config.HttpConfig;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {

    private static volatile RetrofitClient instance;
    private static APIService apiService;

    public RetrofitClient() {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(10, TimeUnit.SECONDS)//HttpConfig.HTTP_TIME
                .readTimeout(HttpConfig.HTTP_TIME,TimeUnit.SECONDS)
                .writeTimeout(HttpConfig.HTTP_TIME,TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                //设置Header
                //.addInterceptor(IntercepterUtil.getHeaderInterceptor())
                //设置token拦截器
                .addInterceptor(IntercepterUtil.tokenInterceptor())
                //设置日志拦截器
                .addInterceptor(IntercepterUtil.logInterceptor())
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .client(client)
                //设置网络请求的Url地址
                .baseUrl(HttpConfig.BASE_URL)
                //设置数据解析器
                .addConverterFactory(GsonConverterFactory.create())
                //设置网络请求适配器，使其支持RxJava与RxAndroid
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        //创建—— 网络请求接口—— 实例
        apiService = retrofit.create(APIService.class);
    }

    public static RetrofitClient getInstance() {
        if (instance == null){
            synchronized (RetrofitClient.class){
                if (instance == null){
                    instance = new RetrofitClient();
                }
            }
        }
        return instance;
    }

    public APIService API(){
        return apiService;
    }

}
